#!/usr/bin/env python
#-*-coding:utf-8-*-

# @author marlondu
# @ env python3

from urllib import request
from http.cookiejar import CookieJar
#import ssl

default_headers = {
	"User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.116 Safari/537.36",
	"Connection":"keep-alive",
	"Accept":"*/*",
	"Accept-Language":"zh-CN,zh;q=0.8,en;q=0.6"
}


class WebClient(object):
	"""docstring for WebClient"""
	def __init__(self):
		super(WebClient, self).__init__()
		self.cj = CookieJar()
		self.cp = request.HTTPCookieProcessor(self.cj)
		self.opener = request.build_opener(self.cp)
		self.charset = 'utf-8'
		self.req = None
		self.timeout = 1000 * 300
		self.useproxy = False
		self.proxy = None
		self.proxytype = 'http'

	def do_get(self,url,headers=None):
		if headers:
			for k,v in self.default_headers.items():
				headers[k] = v
			self.req = request.Request(url,headers=headers)
		else:
			self.req = request.Request(url,headers=default_headers)
		if self.useproxy:
			self.req.set_proxy(self.proxy,self.proxytype)
		#context = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
		#context.verify_mode = ssl.CERT_REQUIRED
		#context.check_hostname = True
		#cert_path = "/etc/ssl/certs/ca-bundle.crt"
		#context.load_verify_locations("E:/download/srca.cer")
		resp = self.opener.open(self.req)
		html = resp.read().decode(self.charset)
		return html

	def do_post(self,url,data,headers=None):
		if headers:
			self.req = request.Request(url,data=data,headers=headers)
		else:
			self.req = request.Request(url,data=data,headers=default_headers)
		if self.useproxy:
			self.req.set_proxy(self.proxy,self.proxytype)
		resp = self.opener.open(self.req)
		html = resp.read().decode(self.charset)
		return html

	def set_proxy(self,host,port,proxytype='http'):
		self.useproxy = True
		self.proxy = ":".join([host,str(port)])
		self.proxytype = proxytype

	def disable_proxy(self):
		self.useproxy = False

	def is_use_proxy(self):
		return self.useproxy
		


